const Koa = require('koa')
const { sequelize, initAllSchema } = require('./database/init')
const config = require('./config')
const { resolve } = require('path')
const glob = require('glob')

const useMiddlewares = app => {
  glob.sync(resolve(__dirname, './middlewares', '**/*.js')).forEach(item => {
    require(item)(app)
  })
}

(async () => {

  await sequelize.authenticate().then(async () => {
    console.log('数据库连接成功')
    initAllSchema()
    // alter: true  force: true
    await sequelize.sync({ alert: true }).then(result => {
      console.log('表同步到数据库成功')
    })
  }).catch(err => {
    console.log('连接失败', err)
  })
  // await initDefaultUser()
  const app = new Koa()

  console.log('挂载socket.io...')
  const server = require('http').Server(app.callback())
  const io = require('socket.io').listen(server)
  require('./socket')(io)

  // 暴露出io可在其他地方做推送功能
  module.exports.io = io

  // console.log('挂载中间件...')
  useMiddlewares(app)

  server.listen(config.server.PORT, () => {
    console.log('正在监听' + config.server.PORT + '端口...')
  })

})()





